//
//  RouteInterceptor.swift
//  XBasicKit
//
//  Created by x on 2024/8/31.
//

// MARK: - 拦截器协议定义

//public protocol RouteInterceptor {
//    /// 返回 false 以阻止导航，返回 true 以继续导航
//    func shouldNavigate(to route: AppRoute) -> Bool
//    func didNavigate(to route: AppRoute)
//    func didFailToNavigate(to route: AppRoute, error: Error)
//}

//// MARK: -  为拦截器提供默认的空实现
//public extension RouteInterceptor {
//    func shouldNavigate(to route: AppRoute) -> Bool { return true }
//    func didNavigate(to route: AppRoute) {}
//    func didFailToNavigate(to route: AppRoute, error: Error) {}
//}
//
//// MARK: - 拦截器包装器定义
//
//public struct RouteInterceptorWrapper {
//    let interceptor: RouteInterceptor
//    let priority: Int
//}

public enum UnionType {
    case appRoute(AppRoute)
    case url(URLConvertible)
    
    
}

// MARK: - 拦截器协议定义
public protocol RouteInterceptor {
    var order: Int { get }  // 拦截器的顺序，值越小优先级越高
    
    // 拦截导航请求
    func intercept(route: UnionType, completion: @escaping (Bool) -> Void)
    
    // 钩子函数：导航前
    func willNavigate(to route: UnionType)
    
    // 钩子函数：导航后
    func didNavigate(to route: UnionType)
    
    // 钩子函数：导航失败
    func didFailToNavigate(to route: UnionType?, error: Error)
}

// 为拦截器提供默认的钩子函数实现
public extension RouteInterceptor {
    func intercept(route: UnionType, completion: @escaping (Bool) -> Void) {
        completion(true)
    }
    
    func willNavigate(to route: UnionType) {}
    func didNavigate(to route: UnionType) {}
    func didFailToNavigate(to route: UnionType?, error: Error) {}
}

// MARK: - 拦截器责任链管理

class InterceptorChain {
    private var interceptors: [RouteInterceptor]
    private var currentIndex: Int = 0

    init(interceptors: [RouteInterceptor]) {
        // 根据 order 对拦截器进行排序
        self.interceptors = interceptors.sorted { $0.order < $1.order }
    }
    
    func proceed(route: UnionType, completion: @escaping (Bool) -> Void) {
        if currentIndex < interceptors.count {
            let interceptor = interceptors[currentIndex]
            currentIndex += 1
            interceptor.willNavigate(to: route)  // 在导航前调用钩子
            interceptor.intercept(route: route) { shouldContinue in
                if shouldContinue {
                    self.proceed(route: route, completion: completion)
                } else {
                    completion(false)
                }
            }
        } else {
            completion(true)
        }
    }
}
